/* @flow */

import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'

let uid = 0

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 * Dep是对Watcher的管理，主要目的就是建立数据和watcher桥梁
 */
export default class Dep {
  // Dep的静态属性target，定义的是watcher
  static target: ?Watcher;
  id: number;
  // 定义的watcher数组
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    // 所有的watcher
    this.subs = []
  }
  
  //newdepids以及depids没有id，就会执行dep.addsub，将watcher放到这个this.subs。
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  depend () {
    // Dep.target表示全局watcher，依赖收集的过程
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // subs aren't sorted in scheduler if not running async
      // we need to sort them now to make sure they fire in correct
      // order
      subs.sort((a, b) => a.id - b.id)
    }
    // 把收集的响应式watcher进行遍历
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
// Dep.target表示全局的watcher，同一时间只有一个Watcher被计算
Dep.target = null
// targetStack是一个类似栈的数组
const targetStack = []

// 
export function pushTarget (target: ?Watcher) {
  // 如果dep.target存在就会把dep.target放在targetStack
  targetStack.push(target)
  // 把_target赋值给dep.target ，目的就是利用栈的数据结构保留当前计算的target
  Dep.target = target
}

export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}
